//
//  RepeatAndDurationViewController.m
//  CoreAnimation
//
//  Created by 张国文 on 16/10/27.
//  Copyright © 2016年 hangzhouyijiyin. All rights reserved.
//

#import "RepeatAndDurationViewController.h"

@interface RepeatAndDurationViewController ()

@property (weak, nonatomic) IBOutlet UIView *backgroundView;
@property (weak, nonatomic) IBOutlet UITextField *repeatTF;
@property (weak, nonatomic) IBOutlet UITextField *durationTF;
@property (weak, nonatomic) IBOutlet UIButton *startButton;
@property (weak, nonatomic) IBOutlet UIButton *stopButton;

@property (nonatomic, strong) CALayer *imageLayer;

@end

@implementation RepeatAndDurationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.imageLayer = [CALayer layer];
    self.imageLayer.frame = CGRectMake(100, 50, 160, 160);
    self.imageLayer.contents = (__bridge id _Nullable)([UIImage imageWithName:@"蒙版"].CGImage);
    [self.backgroundView.layer addSublayer:_imageLayer];
    // 默认为1.0秒，重复一次
    self.repeatTF.text = @"1";
    self.durationTF.text = @"1";
    
    UITapGestureRecognizer *tapGesOfBackgroundView = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesOfBackgroundView:)];
    [self.backgroundView addGestureRecognizer:tapGesOfBackgroundView];
    
}

- (void)tapGesOfBackgroundView:(UITapGestureRecognizer *)tapGes
{
    [self.view endEditing:YES];
}

- (IBAction)start:(id)sender {
    CGFloat repeatCount = [self.repeatTF.text floatValue];
    CGFloat duration = [self.durationTF.text floatValue];
    CABasicAnimation *animation = [CABasicAnimation animation];
    animation.keyPath = @"transform.rotation.z";
    animation.duration = duration;
    animation.repeatCount = repeatCount;
    animation.toValue = @(2 * M_PI);
    animation.autoreverses = YES; // 此属性是每轮动画都会翻转
 //   animation.repeatDuration = 3.0; // 此属性是动画的持续时间，一般不用，使用的时候要和duration配合使用
    [self.imageLayer addAnimation:animation forKey:@"changeRotation.z"];
}

- (IBAction)stop:(id)sender {
    if ([self.imageLayer animationForKey:@"changeRotation.z"]) {
        [self.imageLayer removeAnimationForKey:@"changeRotation.z"];
    }
}

- (void)setControlEnabled:(BOOL)enabled
{
    for (UIControl *control in @[self.durationTF, self.repeatTF, self.startButton, self.stopButton]) {
        control.enabled = enabled;
        control.alpha = enabled? 1.0f:0.3f;
    }
}


@end
